const tagDao = require("@/dao/tag");
const z_base_Dao = require("@/dao/z_base");
const tagModal = require("@/model/tag");
const ArticleModal = require("@/model/Article");
const { ErrorCode } = require("@/utils/r/code");
const { cloneDeep } = require("lodash");

const tag = {
  async GetOption() {
    let res = await tagDao.GetOption();
    console.log(res);
    return res;
    // return new Promise((resolve, reject) => {
    //   try {
    //     resolve(tagDao.GetOption());
    //   } catch (error) {
    //     reject(error);
    //   }
    // });
  },
  async GetList(query) {
    const { datas, total } = await tagDao.GetList(query);
    return {
      total,
      pageData: datas,
      pageSize: +query.page_size,
      pageNum: +query.page_num,
    };
  },
  async SaveOrUpdate(body) {
    //创建前端不传递id，更新前端传递id
    const exist = await z_base_Dao.GetOne(tagModal.TagVO, { name: body.name });

    if (exist && body?.id !== exist?.id) {
      //代表新插入的标签已经存在
      return ErrorCode.ERROR_TAG_EXIST;
    }
    const tag = cloneDeep(body);
    tag.updated_at = new Date().toLocaleString();
    if (body?.id) {
      //更新
      await z_base_Dao.Update(tagModal.TagVO, tag, { id: body.id });
    } else {
      //创建
      tag.created_at = new Date().toLocaleString();
      await z_base_Dao.Create(tagModal.TagVO, tag);
    }

    return ErrorCode.OK;
  },
  async Delete(ids) {
    //删除一个标签，首先需要判断该标签是否用于文章列表中
    const total = await z_base_Dao.Count(
      ArticleModal.ArticleTag,
      "tag_id in (:ids)", //方便处理ids为数组的情况
      ids
    );
    if (total > 0) {
      //代表要删除的标签被文章使用，不能删除
      return ErrorCode.ERROR_TAG_ART_EXIST;
    }
    await z_base_Dao.Delete(tagModal.TagVO, { id: ids });
    return ErrorCode.OK;
  },
  async GetFrontList() {
    let { datas } = await tagDao.GetList();
    return {
      list: datas,
      total: datas.length,
    };
  },
};

module.exports = tag;
